/**
 * @Date 2023-02-04 10:54:22
 * @Remark
 */

import dayjs, { Dayjs } from "dayjs";
import _ from "lodash";

// 格式化时间
function format(
  time: Date | number | string | Dayjs | null | undefined = new Date(),
  type: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 = 0,
): string {
  let pattern = "";
  switch (type) {
    case 0:
      pattern = "YYYY-MM-DD";
      break;
    case 1:
      pattern = "YYYY-MM-DD HH:mm:ss";
      break;
    case 2:
      pattern = "YYYY-MM";
      break;
    case 3:
      pattern = "YYYY";
      break;
    case 4:
      pattern = "YYYY-MM-DD HH:00:00";
      break;
    case 5:
      pattern = "HH:mm";
      break;
    case 6:
      pattern = "YYYY-MM-DD HH:mm";
      break;
    case 7:
      pattern = "YYYY-MM-DD 00:00:00";
      break;
    default:
      pattern = "YYYY-MM-DD";
      break;
  }
  if (dayjs.isDayjs(time)) {
    return time.format(pattern);
  }
  return dayjs(time).format(pattern);
}

// 获得时间戳(毫秒)
function getTime(time: dayjs.Dayjs | Date | number = new Date()): number {
  if (dayjs.isDayjs(time)) {
    return time.valueOf();
  }
  return dayjs(time).valueOf();
}

// 获得一个日期区间
function formatRangeDate(
  date?: Dayjs[],
  type: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 = 0,
) {
  if (!_.isArray(date) || date.length !== 2) {
    return [];
  }
  const [b, e] = date;
  return [format(b, type), format(e, type)];
}

const timeUtils = {
  format,
  formatRangeDate,
  getTime,
};

export default timeUtils;
